<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  <!-- 谷歌收录 -->
  <meta name="google-site-verification" content="-5hl8eC4wfapGZhZouwMVUcKG0iaynijVRJbqVlzXm4" />
  
  
  <title>Go语言什么时候使用指针 | 鴻塵</title>
  <meta name="description" content="img {         display: inline !important;     }     文章说明文章作者：鴻塵文章链接：https:&#x2F;&#x2F;hwame.top&#x2F;20220323&#x2F;when-to-use-pointer-in-go.html原文链接：https:&#x2F;&#x2F;mp.weixin.qq.com&#x2F;s&#x2F;FQ83qRBb985FHB-0ttIYCQ文章说明：文章使用Go程序将微信">
<meta property="og:type" content="article">
<meta property="og:title" content="Go语言什么时候使用指针">
<meta property="og:url" content="https://hwame.top/20220323/when-to-use-pointer-in-go.html">
<meta property="og:site_name" content="鴻塵">
<meta property="og:description" content="img {         display: inline !important;     }     文章说明文章作者：鴻塵文章链接：https:&#x2F;&#x2F;hwame.top&#x2F;20220323&#x2F;when-to-use-pointer-in-go.html原文链接：https:&#x2F;&#x2F;mp.weixin.qq.com&#x2F;s&#x2F;FQ83qRBb985FHB-0ttIYCQ文章说明：文章使用Go程序将微信">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img.shields.io/badge/copyright-原创-fff">
<meta property="og:image" content="https://img.shields.io/badge/name-Go语言圈-fff">
<meta property="og:image" content="https://img.shields.io/badge/date-2022--03--22%2018:00:00-fff">
<meta property="og:image" content="https://mmbiz.qpic.cn/mmbiz_png/HvRgjyfjzzbS0SgWK0yOicRmkTcHib69Uia3t6QY1wxRudKTQbdLKPBzvWZSBOkXNq8pAc7Jr4LWDiaibqicHQUib6Yww/640?wx_fmt=png">
<meta property="og:image" content="https://mmbiz.qpic.cn/mmbiz_gif/HvRgjyfjzzbS0SgWK0yOicRmkTcHib69Uiat5cPkKPaQV0ib9jPjabSe4xskicA1dJQSV8IibKHMgicez2Oxy8hXjpqiaw/640?wx_fmt=gif">
<meta property="og:image" content="https://mmbiz.qpic.cn/mmbiz_png/HvRgjyfjzzagmtamicekg2t5yZRCcvGiboBFzESicSxTywtBjb9IibxVtfOBBvBr5Zriajv0XdgYK0oqu2ZXicudLUkw/640?wx_fmt=png">
<meta property="article:published_time" content="2022-03-23T12:49:57.000Z">
<meta property="article:modified_time" content="2022-03-23T15:48:45.000Z">
<meta property="article:author" content="鴻塵">
<meta property="article:tag" content="Go">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img.shields.io/badge/copyright-原创-fff">
  <!-- Canonical links -->
  <link rel="canonical" href="https://hwame.top/20220323/when-to-use-pointer-in-go.html">
  
    <link rel="alternate" href="true" title="鴻塵" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/css/style.css">

  
    <link href="//cdn.jsdelivr.net/npm/katex@0.9.0/dist/katex.min.css" rel="stylesheet">
  
  
  
    <link href="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css" rel="stylesheet">
  
  
<meta name="generator" content="Hexo 5.4.2"></head>


<script src="https://cdn.jsdelivr.net/gh/bobcn/hexo_resize_image.js@master/hexo_resize_image.js"></script>
<body class="main-center theme-purple" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="https://hwame.top" target="_blank">
          <img class="img-circle img-rotate" src="https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">鴻塵</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">Pythoner, Data Analyst</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> 湖北-武汉</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav menu-highlight">
        
        
        <li class="menu-item menu-item-home">
          <a href="/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">首页</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">归档</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/categories">
            
            <i class="icon icon-folder-open"></i>
            
            <span class="menu-title">分类</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">标签</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-repository">
          <a href="/repository">
            
            <i class="icon icon-project"></i>
            
            <span class="menu-title">资源</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-gallery">
          <a href="/gallery">
            
            <i class="icon icon-delicious"></i>
            
            <span class="menu-title">相册</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-links">
          <a href="/links">
            
            <i class="icon icon-friendship"></i>
            
            <span class="menu-title">友链</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-about">
          <a href="/about">
            
            <i class="icon icon-cup-fill"></i>
            
            <span class="menu-title">关于</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/hwame" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="https://weibo.com/hwamei" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="https://www.zhihu.com/people/hwame" target="_blank" title="Zhihu" data-toggle=tooltip data-placement=top><i class="icon icon-zhihu"></i></a></li>
        
        <li><a href="https://segmentfault.com/u/hwame" target="_blank" title="Segmentfault" data-toggle=tooltip data-placement=top><i class="icon icon-segmentfault"></i></a></li>
        
        <li><a href="https://gitee.com/hwame" target="_blank" title="Gitee" data-toggle=tooltip data-placement=top><i class="icon icon-gitee"></i></a></li>
        
        <li><a href="/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-stackexchange"></i>公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>欢迎来到鴻塵的博客!<br>鴻塵的<u><a target="_blank" rel="noopener" href="https://weibo.com/hwamei" style="color:#E541E5;">微博</a></u>主页，鴻塵的<u><a target="_blank" rel="noopener" href="https://github.com/hwame" style="color:#E541E5;">Github</a></u>主页，如果我可以忘记的<u><a target="_blank" rel="noopener" href="https://www.zhihu.com/people/hwame" style="color:#E541E5;">知乎</a></u>主页。</p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-tags"></i>标签云</h3>
    <div class="widget-body tagcloud">
      <a href="/tags/CentOS/" style="font-size: 13px; color: #fff">CentOS</a> <a href="/tags/Go/" style="font-size: 13.2px; color: #fff">Go</a> <a href="/tags/Hexo/" style="font-size: 13.8px; color: #fff">Hexo</a> <a href="/tags/Linux/" style="font-size: 14px; color: #fff">Linux</a> <a href="/tags/Linux%E9%83%A8%E7%BD%B2/" style="font-size: 13px; color: #fff">Linux部署</a> <a href="/tags/MongoDB/" style="font-size: 13.4px; color: #fff">MongoDB</a> <a href="/tags/Spark/" style="font-size: 13px; color: #fff">Spark</a> <a href="/tags/matplotlib/" style="font-size: 13.2px; color: #fff">matplotlib</a> <a href="/tags/miscellanea/" style="font-size: 13.6px; color: #fff">miscellanea</a> <a href="/tags/python/" style="font-size: 14px; color: #fff">python</a> <a href="/tags/shell/" style="font-size: 13.6px; color: #fff">shell</a> <a href="/tags/%E5%A4%A7%E6%95%B0%E6%8D%AE/" style="font-size: 13px; color: #fff">大数据</a> <a href="/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" style="font-size: 13px; color: #fff">数据结构与算法</a> <a href="/tags/%E7%88%AC%E8%99%AB/" style="font-size: 13px; color: #fff">爬虫</a>
    </div>
  </div>

<script type="text/javascript">
    var everytag=document.getElementsByClassName("widget-body tagcloud")[0].children;
    for (var i = everytag.length - 1; i >= 0; i--) {
    	var r=Math.floor(Math.random()*255);
        var g=Math.floor(Math.random()*255);
        var b=Math.floor(Math.random()*255);
        everytag[i].style.background = "rgb("+r+","+g+","+b+")";
    }
</script>
    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-folder-open"></i>分类</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Go/">Go</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Hexo/">Hexo</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Linux/">Linux</a><span class="category-list-count">8</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/MongoDB/">MongoDB</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/miscellanea/">miscellanea</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/python/">python</a><span class="category-list-count">7</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/">数据结构与算法</a><span class="category-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-archives-fill"></i>归档</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2022/">2022</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/">2021</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/">2020</a><span class="archive-list-count">17</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-shu-fill"></i>最新文章</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled ">
        
          <li>
            
            <div class="item-thumb">
              <a href="/20220327/channel-and-goroutine-in-go.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/icon-golang.jpeg)" alt="Go语言中的通道" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Go/">Go</a>
              </p>
              <p class="item-title">
                <a href="/20220327/channel-and-goroutine-in-go.html" class="title">Go语言中的通道</a>
              </p>
              <p class="item-date">
                <time datetime="2022-03-27T11:06:16.000Z" itemprop="datePublished">2022-03-27</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220323/when-to-use-pointer-in-go.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/icon-golang.jpeg)" alt="Go语言什么时候使用指针" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Go/">Go</a>
              </p>
              <p class="item-title">
                <a href="/20220323/when-to-use-pointer-in-go.html" class="title">Go语言什么时候使用指针</a>
              </p>
              <p class="item-date">
                <time datetime="2022-03-23T12:49:57.000Z" itemprop="datePublished">2022-03-23</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220228/awesome-images-in-markdown.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg)" alt="Markdown中图片的高级用法" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/miscellanea/">miscellanea</a>
              </p>
              <p class="item-title">
                <a href="/20220228/awesome-images-in-markdown.html" class="title">Markdown中图片的高级用法</a>
              </p>
              <p class="item-date">
                <time datetime="2022-02-28T15:27:50.000Z" itemprop="datePublished">2022-02-28</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220116/shell-regular-expression.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/linux-icon.png)" alt="Shell正则表达式" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Linux/">Linux</a>
              </p>
              <p class="item-title">
                <a href="/20220116/shell-regular-expression.html" class="title">Shell正则表达式</a>
              </p>
              <p class="item-date">
                <time datetime="2022-01-16T14:13:05.000Z" itemprop="datePublished">2022-01-16</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20211009/install-linux-on-android-phone.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg)" alt="如何在安卓手机上安装Linux发行版" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/miscellanea/">miscellanea</a>
              </p>
              <p class="item-title">
                <a href="/20211009/install-linux-on-android-phone.html" class="title">如何在安卓手机上安装Linux发行版</a>
              </p>
              <p class="item-date">
                <time datetime="2021-10-09T15:16:37.000Z" itemprop="datePublished">2021-10-09</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <nav id="toc" class="article-toc">
      <h3 class="toc-title">文章目录</h3>
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#Go%E8%AF%AD%E8%A8%80%E4%BB%80%E4%B9%88%E6%97%B6%E5%80%99%E8%AF%A5%E4%BD%BF%E7%94%A8%E6%8C%87%E9%92%88%EF%BC%9F%E6%8C%87%E9%92%88%E4%BD%BF%E7%94%A8%E5%88%86%E6%9E%90%E4%B8%8E%E8%AE%B2%E8%A7%A3"><span class="toc-number">1.</span> <span class="toc-text">Go语言什么时候该使用指针？指针使用分析与讲解</span></a></li></ol>
    </nav>
  </div>
</aside>

<main class="main" role="main">
  <div class="content">
  <article id="post-when-to-use-pointer-in-go" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      Go语言什么时候使用指针
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar"></i>
	<a href="/20220323/when-to-use-pointer-in-go.html" class="article-date">
	  发布于 <time datetime="2022-03-23T12:49:57.000Z" itemprop="datePublished">2022-03-23</time>
	</a>
</span>
<span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/20220323/when-to-use-pointer-in-go.html" class="article-date">
	  更新于 <time datetime="2022-03-23T15:48:45.000Z" itemprop="dateUpdated">2022-03-23</time>
	</a>
</span>
        
  <span class="article-category">
    <i class="icon icon-folder"></i>
    <a class="article-category-link" href="/categories/Go/">Go</a>
  </span>

        
  <span class="article-tag">
    <i class="icon icon-tags"></i>
	<a class="article-tag-link-link" href="/tags/Go/" rel="tag">Go</a>
  </span>


        

	<span class="article-read hidden-xs">
    	<i class="icon icon-eye-fill" aria-hidden="true"></i>
    	<span id="/20220323/when-to-use-pointer-in-go.html" class="leancloud_visitors"  data-flag-title="Go语言什么时候使用指针">
			<span class="leancloud-visitors-count">0</span>
		</span>
    </span>

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/20220323/when-to-use-pointer-in-go.html#comments" class="article-comment-link">评论</a></span>
        
	
		<span class="post-wordcount hidden-xs" itemprop="wordCount">字数统计: 2.8k(字)</span>
	
	
		<span class="post-readcount hidden-xs" itemprop="timeRequired">阅读时长: 11(分)</span>
	

      </div>
      <div style="background-color:#D7BDE2;border:1px solid #D7BDE2;border-radius:10px;padding:5px">
          <b>温馨提示</b>：点击页面下方<i style="color:red" class="icon icon-anchor"></i>以展开或折叠目录
      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <style>
    img {
        display: inline !important;
    }
</style>


<blockquote>
<p><font size=5><b>文章说明</b></font><br><strong>文章作者：</strong><a href="https://hwame.top">鴻塵</a><br><strong>文章链接：</strong><a href="https://hwame.top/20220323/when-to-use-pointer-in-go.html">https://hwame.top/20220323/when-to-use-pointer-in-go.html</a><br><strong>原文链接：</strong><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/FQ83qRBb985FHB-0ttIYCQ">https://mp.weixin.qq.com/s/FQ83qRBb985FHB-0ttIYCQ</a><br><strong>文章说明：</strong>文章使用Go程序将<a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/FQ83qRBb985FHB-0ttIYCQ">微信公众号文章</a>转换为Markdown格式。<br><strong>参考资料：</strong></p>
<ul>
<li><a target="_blank" rel="noopener" href="https://mp.weixin.qq.com/s/FQ83qRBb985FHB-0ttIYCQ">Go语言什么时候该使用指针？指针使用分析与讲解</a></li>
<li><a target="_blank" rel="noopener" href="https://www.jb51.net/article/233949.htm">Go语言什么时候该使用指针</a></li>
</ul>
</blockquote>
<hr>
<h2 id="Go语言什么时候该使用指针？指针使用分析与讲解"><a href="#Go语言什么时候该使用指针？指针使用分析与讲解" class="headerlink" title="Go语言什么时候该使用指针？指针使用分析与讲解"></a>Go语言什么时候该使用指针？指针使用分析与讲解</h2><p><img src="https://img.shields.io/badge/copyright-原创-fff" alt="">        <img src="https://img.shields.io/badge/name-Go语言圈-fff" alt="">    <img src="https://img.shields.io/badge/date-2022--03--22%2018:00:00-fff" alt=""></p>
<p>收录于话题<code>#为什么要学Go语言</code> 47个   </p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_png/HvRgjyfjzzbS0SgWK0yOicRmkTcHib69Uia3t6QY1wxRudKTQbdLKPBzvWZSBOkXNq8pAc7Jr4LWDiaibqicHQUib6Yww/640?wx_fmt=png" alt="picture"></p>
<p><img src="https://mmbiz.qpic.cn/mmbiz_gif/HvRgjyfjzzbS0SgWK0yOicRmkTcHib69Uiat5cPkKPaQV0ib9jPjabSe4xskicA1dJQSV8IibKHMgicez2Oxy8hXjpqiaw/640?wx_fmt=gif" alt="picture"></p>
<p> <strong>什么是指针</strong><br>我们都知道，程序运行时的数据是存放在内存中的，每一个存储在内存中的数据都有一个编号，这个编号就是内存地址。我们可以根据这个内存地址来找到内存中存储的数据，而内存地址可以被赋值给一个指针。我们也可以简单的理解为指针就是内存地址。<br> <strong>指针的声明和定义</strong><br>在Go语言中，获取一个指针，直接使用取地址符<code>&amp;</code>就可以。<br>示例：<br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    name := <span class="string">&quot;Go语言圈&quot;</span></span><br><span class="line">    nameP := &amp;name <span class="comment">//取地址</span></span><br><span class="line">    fmt.Println(<span class="string">&quot;name变量值为：&quot;</span>, name)</span><br><span class="line">    fmt.Println(<span class="string">&quot;name变量的内存地址为：&quot;</span>, nameP)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//运行结果：</span></span><br><span class="line"><span class="comment">//name变量值为：Go语言圈</span></span><br><span class="line"><span class="comment">//name变量的内存地址为： 0xc00004e240</span></span><br></pre></td></tr></table></figure></p>
<p>nameP 指针的类型是  <code>*string</code><br>Go语言中，<code>*</code> 类型名表示一个对应的指针类型<br><img src="https://mmbiz.qpic.cn/mmbiz_png/HvRgjyfjzzagmtamicekg2t5yZRCcvGiboBFzESicSxTywtBjb9IibxVtfOBBvBr5Zriajv0XdgYK0oqu2ZXicudLUkw/640?wx_fmt=png" alt="picture"></p>
<p>从上面表格可以看到：</p>
<ul>
<li>普通变量 name 的值是Go语言圈，存放在内存地址为 0xc00004e240 的内存中</li>
<li>指针变量 namep 的值是普通变量的内存地址 0xc00004e240</li>
<li>指针变量 nameP 的值存放在 内存地址为 0xc00004e360 的内存中</li>
<li>普通变量存的是数据，指针变量存的是数据的地址</li>
</ul>
<p> <strong>var 关键字声明</strong><br>我们也可以使用 var 关键字声明<br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> nameP *<span class="type">string</span></span><br><span class="line">nameP = &amp;name</span><br></pre></td></tr></table></figure></p>
<p> <strong>new 函数声明</strong><br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">nameP := <span class="built_in">new</span>(<span class="type">string</span>)</span><br><span class="line">nameP = &amp;name</span><br></pre></td></tr></table></figure></p>
<p>可以传递类型给这个内置的  <code>new</code>  函数，它会返回对应的指针类型。<br> <strong>指针的操作</strong><br>这里强调一下：<br>指针变量是一个变量，这个变量的值是指针（内存地址）！<br>指针变量是一个变量，这个变量的值是指针（内存地址）！<br>指针变量是一个变量，这个变量的值是指针（内存地址）！<br>获取指针指向的值：<br>只需要在指针变量前加 <code>*</code> 号即可获得指针变量值所对应的数据：<br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">nameV := *nameP</span><br><span class="line">fmt.Println(<span class="string">&quot;nameP指针指向的值为:&quot;</span>, nameV)</span><br><span class="line"><span class="comment">//nameP指针指向的值为: Go语言圈</span></span><br></pre></td></tr></table></figure></p>
<p>修改指针指向的值：<br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">*nameP = <span class="string">&quot;公众号:Go语言圈&quot;</span></span><br><span class="line"><span class="comment">//修改指针指向的值</span></span><br><span class="line"></span><br><span class="line">fmt.Println(<span class="string">&quot;nameP指针指向的值为:&quot;</span>,*nameP)</span><br><span class="line">fmt.Println(<span class="string">&quot;name变量的值为:&quot;</span>,name)</span><br><span class="line"></span><br><span class="line"><span class="comment">//运行结果：</span></span><br><span class="line"><span class="comment">//nameP指针指向的值为: 公众号:Go语言圈</span></span><br><span class="line"><span class="comment">//name变量的值为: 公众号:Go语言圈</span></span><br></pre></td></tr></table></figure></p>
<ul>
<li>我们发现nameP 指针指向的值被改变了，变量 name 的值也被改变了</li>
<li>因为变量 name 存储数据的内存就是指针 nameP 指向的内存，这块内存被 nameP 修改后，变量 name 的值也被修改了。</li>
</ul>
<p>通过 var 关键字直接定义的指针变量是不能进行赋值操作的，因为它的值为 nil，也就是还没有指向的内存地址<br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//错误示例</span></span><br><span class="line"><span class="keyword">var</span> intP *<span class="type">int</span></span><br><span class="line">*intP = <span class="number">10</span></span><br><span class="line"><span class="comment">//错误，应该先给分配一块内存，内存地址作为变量 intP 的值，这个内存就可以存放 10 了。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//应该使用</span></span><br><span class="line"><span class="keyword">var</span> intP *<span class="type">int</span><span class="comment">//声明int类型的指针变量 intP</span></span><br><span class="line">intP = <span class="built_in">new</span>(<span class="type">int</span>) <span class="comment">// 给指针分配一块内存</span></span><br><span class="line">*intP = <span class="number">66</span> </span><br><span class="line">fmt.Println(<span class="string">&quot;:::&quot;</span>,intP)  <span class="comment">//::: 0xc0000ac088</span></span><br><span class="line">fmt.Println(*intP) <span class="comment">//66</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//简短写法</span></span><br><span class="line"><span class="keyword">var</span> intP := <span class="built_in">new</span>(<span class="type">int</span>)</span><br><span class="line">*intP=<span class="number">66</span></span><br></pre></td></tr></table></figure></p>
<p> <strong>指针参数</strong><br>当给一个函数使用指针作为参数的时候，就可以在函数中，通过形参改变实参的值：<br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    name := <span class="string">&quot;疯子&quot;</span></span><br><span class="line">    modify(&amp;name)</span><br><span class="line">    fmt.Println(<span class="string">&quot;name的值为:&quot;</span>,name)</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">modify</span><span class="params">(name *<span class="type">string</span>)</span></span>  &#123;</span><br><span class="line">    *name = <span class="string">&quot;wucs&quot;</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//运行结果：</span></span><br><span class="line"><span class="comment">//name的值为: wucs</span></span><br></pre></td></tr></table></figure></p>
<p> <strong>指针接收者</strong> </p>
<ul>
<li>如果接收者类型是 map、slice、channel 这类引用类型，不使用指针；</li>
<li>如果需要修改接收者，那么需要使用指针；</li>
<li>如果接收者是比较大的类型，可以考虑使用指针，因为内存拷贝廉价，所以效率高。</li>
</ul>
<p><strong>普通指针</strong><br>和C语言一样, 允许用一个变量来存放其它变量的地址, 这种专门用于存储其它变量地址的变量, 我们称之为指针变量.<br>和C语言一样, Go语言中的指针无论是什么类型占用内存都一样(32位4个字节, 64位8个字节)<br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">&quot;fmt&quot;</span></span><br><span class="line">    <span class="string">&quot;unsafe&quot;</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">var</span> p1 *<span class="type">int</span>;</span><br><span class="line">    <span class="keyword">var</span> p2 *<span class="type">float64</span>;</span><br><span class="line">    <span class="keyword">var</span> p3 *<span class="type">bool</span>;</span><br><span class="line"></span><br><span class="line">    fmt.Println(unsafe.Sizeof(p1)) <span class="comment">// 8</span></span><br><span class="line">    fmt.Println(unsafe.Sizeof(p2)) <span class="comment">// 8</span></span><br><span class="line">    fmt.Println(unsafe.Sizeof(p3)) <span class="comment">// 8</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>和C语言一样, 只要一个指针变量保存了另一个变量对应的内存地址, 那么就可以通过<code>*</code>来访问指针变量指向的存储空间<br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> (</span><br><span class="line">    <span class="string">&quot;fmt&quot;</span></span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="comment">// 1.定义一个普通变量</span></span><br><span class="line">    <span class="keyword">var</span> num <span class="type">int</span> = <span class="number">666</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 2.定义一个指针变量</span></span><br><span class="line">    <span class="keyword">var</span> p *<span class="type">int</span> = &amp;num</span><br><span class="line">    fmt.Printf(<span class="string">&quot;%p\n&quot;</span>, &amp;num) <span class="comment">// 0xc042064080</span></span><br><span class="line">    fmt.Printf(<span class="string">&quot;%p\n&quot;</span>, p) <span class="comment">// 0xc042064080</span></span><br><span class="line">    fmt.Printf(<span class="string">&quot;%T\n&quot;</span>, p) <span class="comment">// *int</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 3.通过指针变量操作指向的存储空间</span></span><br><span class="line">    *p = <span class="number">888</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 4.指针变量操作的就是指向变量的存储空间</span></span><br><span class="line">    fmt.Println(num) <span class="comment">// 888</span></span><br><span class="line">    fmt.Println(*p) <span class="comment">// 888</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p> <strong>指向数组指针</strong><br>在Go语言中通过数组名无法直接获取数组的内存地址<br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"><span class="keyword">import</span> <span class="string">&quot;fmt&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">var</span> arr [<span class="number">3</span>]<span class="type">int</span> = [<span class="number">3</span>]<span class="type">int</span>&#123;<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>&#125;</span><br><span class="line">    fmt.Printf(<span class="string">&quot;%p\n&quot;</span>, arr) <span class="comment">// 乱七八糟东西</span></span><br><span class="line">    fmt.Printf(<span class="string">&quot;%p\n&quot;</span>, &amp;arr) <span class="comment">// 0xc0420620a0</span></span><br><span class="line">    fmt.Printf(<span class="string">&quot;%p\n&quot;</span>, &amp;arr[<span class="number">0</span>]) <span class="comment">// 0xc0420620a0</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在Go语言中, 因为只有数据类型一模一样才能赋值, 所以只能通过<code>&amp;数组名</code>赋值给指针变量, 才代表指针变量指向了这个数组<br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> <span class="string">&quot;fmt&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="comment">// 1.错误, 在Go语言中必须类型一模一样才能赋值</span></span><br><span class="line">    <span class="comment">// arr类型是[3]int, p1的类型是*[3]int</span></span><br><span class="line">    <span class="keyword">var</span> p1 *[<span class="number">3</span>]<span class="type">int</span></span><br><span class="line">    fmt.Printf(<span class="string">&quot;%T\n&quot;</span>, arr)</span><br><span class="line">    fmt.Printf(<span class="string">&quot;%T\n&quot;</span>, p1)</span><br><span class="line">    p1 = arr <span class="comment">// 报错</span></span><br><span class="line">    p1[<span class="number">1</span>] = <span class="number">6</span></span><br><span class="line">    fmt.Println(arr[<span class="number">1</span>])</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 2.正确, &amp;arr的类型是*[3]int, p2的类型也是*[3]int</span></span><br><span class="line">    <span class="keyword">var</span> p2 *[<span class="number">3</span>]<span class="type">int</span></span><br><span class="line">    fmt.Printf(<span class="string">&quot;%T\n&quot;</span>, &amp;arr)</span><br><span class="line">    fmt.Printf(<span class="string">&quot;%T\n&quot;</span>, p2)</span><br><span class="line">    p2 = &amp;arr</span><br><span class="line">    p2[<span class="number">1</span>] = <span class="number">6</span></span><br><span class="line">    fmt.Println(arr[<span class="number">1</span>])</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 3.错误, &amp;arr[0]的类型是*int, p3的类型也是*[3]int</span></span><br><span class="line">    <span class="keyword">var</span> p3 *[<span class="number">3</span>]<span class="type">int</span></span><br><span class="line">    fmt.Printf(<span class="string">&quot;%T\n&quot;</span>, &amp;arr[<span class="number">0</span>])</span><br><span class="line">    fmt.Printf(<span class="string">&quot;%T\n&quot;</span>, p3)</span><br><span class="line">    p3 = &amp;arr[<span class="number">0</span>] <span class="comment">// 报错</span></span><br><span class="line">    p3[<span class="number">1</span>] = <span class="number">6</span></span><br><span class="line">    fmt.Println(arr[<span class="number">1</span>])</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>注意点:<br>Go语言中的指针, 不支持C语言中的<code>+1</code> <code>-1</code>和<code>++</code> <code>–-</code> 操作<br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"><span class="keyword">import</span> <span class="string">&quot;fmt&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">var</span> arr [<span class="number">3</span>]<span class="type">int</span> = [<span class="number">3</span>]<span class="type">int</span>&#123;<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>&#125;</span><br><span class="line">    <span class="keyword">var</span> p *[<span class="number">3</span>]<span class="type">int</span></span><br><span class="line">    p = &amp;arr</span><br><span class="line"></span><br><span class="line">    fmt.Printf(<span class="string">&quot;%p\n&quot;</span>, &amp;arr) <span class="comment">// 0xc0420620a0</span></span><br><span class="line">    fmt.Printf(<span class="string">&quot;%p\n&quot;</span>, p) <span class="comment">// 0xc0420620a0</span></span><br><span class="line">    fmt.Println(&amp;arr) <span class="comment">// &amp;[1 3 5]</span></span><br><span class="line">    fmt.Println(p) <span class="comment">// &amp;[1 3 5]</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 指针指向数组之后操作数组的几种方式</span></span><br><span class="line">    <span class="comment">// 1.直接通过数组名操作</span></span><br><span class="line">    arr[<span class="number">1</span>] = <span class="number">6</span></span><br><span class="line">    fmt.Println(arr[<span class="number">1</span>])</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 2.通过指针间接操作</span></span><br><span class="line">    (*p)[<span class="number">1</span>] = <span class="number">7</span></span><br><span class="line">    fmt.Println((*p)[<span class="number">1</span>])</span><br><span class="line">    fmt.Println(arr[<span class="number">1</span>])</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 3.通过指针间接操作</span></span><br><span class="line">    p[<span class="number">1</span>] = <span class="number">8</span></span><br><span class="line">    fmt.Println(p[<span class="number">1</span>])</span><br><span class="line">    fmt.Println(arr[<span class="number">1</span>])</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 注意点: Go语言中的指针, 不支持+1 -1和++ --操作</span></span><br><span class="line">    *(p + <span class="number">1</span>) = <span class="number">9</span> <span class="comment">// 报错</span></span><br><span class="line">    fmt.Println(*p++) <span class="comment">// 报错</span></span><br><span class="line">    fmt.Println(arr[<span class="number">1</span>])</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p> <strong>指向切片的指针</strong><br>值得注意点的是切片的本质就是一个指针指向数组, 所以指向切片的指针是一个二级指针<br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"><span class="keyword">import</span> <span class="string">&quot;fmt&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="comment">// 1.定义一个切片</span></span><br><span class="line">    <span class="keyword">var</span> sce[]<span class="type">int</span> = []<span class="type">int</span>&#123;<span class="number">1</span>, <span class="number">3</span>, <span class="number">5</span>&#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 2.打印切片的地址</span></span><br><span class="line">    <span class="comment">// 切片变量中保存的地址, 也就是指向的那个数组的地址 sce = 0xc0420620a0</span></span><br><span class="line">    fmt.Printf(<span class="string">&quot;sce = %p\n&quot;</span>,sce )</span><br><span class="line">    fmt.Println(sce) <span class="comment">// [1 3 5]</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 切片变量自己的地址, &amp;sce = 0xc04205e3e0</span></span><br><span class="line">    fmt.Printf(<span class="string">&quot;&amp;sce = %p\n&quot;</span>,&amp;sce )</span><br><span class="line">    fmt.Println(&amp;sce) <span class="comment">// &amp;[1 3 5]</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 3.定义一个指向切片的指针</span></span><br><span class="line">    <span class="keyword">var</span> p *[]<span class="type">int</span></span><br><span class="line">    <span class="comment">// 因为必须类型一致才能赋值, 所以将切片变量自己的地址给了指针</span></span><br><span class="line">    p = &amp;sce</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 4.打印指针保存的地址</span></span><br><span class="line">    <span class="comment">// 直接打印p打印出来的是保存的切片变量的地址 p = 0xc04205e3e0</span></span><br><span class="line">    fmt.Printf(<span class="string">&quot;p = %p\n&quot;</span>, p)</span><br><span class="line">    fmt.Println(p) <span class="comment">// &amp;[1 3 5]</span></span><br><span class="line">    <span class="comment">// 打印*p打印出来的是切片变量保存的地址, 也就是数组的地址 *p = 0xc0420620a0</span></span><br><span class="line">    fmt.Printf(<span class="string">&quot;*p = %p\n&quot;</span>, *p)</span><br><span class="line">    fmt.Println(*p) <span class="comment">// [1 3 5]</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">// 5.修改切片的值</span></span><br><span class="line">    <span class="comment">// 通过*p找到切片变量指向的存储空间(数组), 然后修改数组中保存的数据</span></span><br><span class="line">    (*p)[<span class="number">1</span>] = <span class="number">666</span></span><br><span class="line">    fmt.Println(sce[<span class="number">1</span>])</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p><strong>指向字典指针</strong><br>与普通指针并无差异<br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"><span class="keyword">import</span> <span class="string">&quot;fmt&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">var</span> dict <span class="keyword">map</span>[<span class="type">string</span>]<span class="type">string</span> = <span class="keyword">map</span>[<span class="type">string</span>]<span class="type">string</span>&#123;<span class="string">&quot;name&quot;</span>:<span class="string">&quot;lnj&quot;</span>, <span class="string">&quot;age&quot;</span>:<span class="string">&quot;33&quot;</span>&#125;</span><br><span class="line">    <span class="keyword">var</span> p *<span class="keyword">map</span>[<span class="type">string</span>]<span class="type">string</span> = &amp;dict</span><br><span class="line">    (*p)[<span class="string">&quot;name&quot;</span>] = <span class="string">&quot;zs&quot;</span></span><br><span class="line">    fmt.Println(dict)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p> <strong>指向结构体指针</strong><br>Go语言中指向结构体的指针和C语言一样<br>结构体和指针<br>创建结构体指针变量有两种方式<br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"><span class="keyword">import</span> <span class="string">&quot;fmt&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Student <span class="keyword">struct</span> &#123;</span><br><span class="line">    name <span class="type">string</span></span><br><span class="line">    age <span class="type">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">  <span class="comment">// 创建时利用取地址符号获取结构体变量地址</span></span><br><span class="line">  <span class="keyword">var</span> p1 = &amp;Student&#123;<span class="string">&quot;lnj&quot;</span>, <span class="number">33</span>&#125;</span><br><span class="line">  fmt.Println(p1) <span class="comment">// &amp;&#123;lnj 33&#125;</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// 通过new内置函数传入数据类型创建</span></span><br><span class="line">  <span class="comment">// 内部会创建一个空的结构体变量, 然后返回这个结构体变量的地址</span></span><br><span class="line">  <span class="keyword">var</span> p2 = <span class="built_in">new</span>(Student)</span><br><span class="line">  fmt.Println(p2) <span class="comment">// &amp;&#123; 0&#125;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p> <strong>利用结构体指针操作结构体属性</strong><br><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> main</span><br><span class="line"><span class="keyword">import</span> <span class="string">&quot;fmt&quot;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">type</span> Student <span class="keyword">struct</span> &#123;</span><br><span class="line">    name <span class="type">string</span></span><br><span class="line">    age <span class="type">int</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">  <span class="keyword">var</span> p = &amp;Student&#123;&#125;</span><br><span class="line">  <span class="comment">// 方式一: 传统方式操作</span></span><br><span class="line">  <span class="comment">// 修改结构体中某个属性对应的值</span></span><br><span class="line">  <span class="comment">// 注意: 由于.运算符优先级比*高, 所以一定要加上()</span></span><br><span class="line">  (*p).name = <span class="string">&quot;lnj&quot;</span></span><br><span class="line">  <span class="comment">// 获取结构体中某个属性对应的值</span></span><br><span class="line">  fmt.Println((*p).name) <span class="comment">// lnj</span></span><br><span class="line"></span><br><span class="line">  <span class="comment">// 方式二: 通过Go语法糖操作</span></span><br><span class="line">  <span class="comment">// Go语言作者为了程序员使用起来更加方便, 在操作指向结构体的指针时可以像操作接头体变量一样通过.来操作</span></span><br><span class="line">  <span class="comment">// 编译时底层会自动转发为(*p).age方式</span></span><br><span class="line">  p.age = <span class="number">33</span></span><br><span class="line">  fmt.Println(p.age) <span class="comment">// 33</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p> <strong>什么情况下使用指针</strong> </p>
<ul>
<li>不要对 map、slice、channel 这类引用类型使用指针；</li>
<li>如果需要修改方法接收者内部的数据或者状态时，需要使用指针；</li>
<li>如果需要修改参数的值或者内部数据时，也需要使用指针类型的参数；</li>
<li>如果是比较大的结构体，每次参数传递或者调用方法都要内存拷贝，内存占用多，这时候可以考虑使用指针；</li>
<li>像 int、bool 这样的小数据类型没必要使用指针；</li>
<li>如果需要并发安全，则尽可能地不要使用指针，使用指针一定要保证并发安全；</li>
<li>指针最好不要嵌套，也就是不要使用一个指向指针的指针，虽然 Go 语言允许这么做，但是这会使你的代码变得异常复杂。</li>
</ul>

      
    </div>
    <div class="article-footer">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-license">
      <strong>文章作者： </strong><a href="https://hwame.top" style="color:#E541E5;"> 鴻塵</a>
    </li>
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://hwame.top/20220323/when-to-use-pointer-in-go.html" title="Go语言什么时候使用指针" target="_blank" rel="external" style="color:#E541E5;">https://hwame.top/20220323/when-to-use-pointer-in-go.html</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用《<a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external" style="color:#E541E5;"><u>CC BY 4.0 CN协议</u></a>》许可协议。转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://hwame.top" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://hwame.top" target="_blank"><span class="text-dark">鴻塵</span><small class="ml-1x">Pythoner, Data Analyst</small></a></h3>
        <div>个人简介：处女座不适合做码农。</div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	
      <div id="vcomments"></div>
    
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/20220327/channel-and-goroutine-in-go.html" title="Go语言中的通道"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a>
    </li>
    
    
    <li class="next">
      <a href="/20220228/awesome-images-in-markdown.html" title="Markdown中图片的高级用法"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
    <li class="toggle-toc">
      <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false" title="文章目录" role="button">
        <span style="color:#C71585">[&nbsp;</span><span style="color:#C71585">文章目录</span>
        <i class="text-collapsed icon icon-anchor"></i>
        <i class="text-in icon icon-close"></i>
        <span style="color:#C71585">]</span>
      </a>
    </li>
    
  </ul>
  
  
  
  <div class="bar-right">
    
    <div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter" data-mobile-sites="weibo,wechat,qq,qzone"></div>
    
  </div>
  </div>
</nav>
  


</main>

  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/hwame" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="https://weibo.com/hwamei" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="https://www.zhihu.com/people/hwame" target="_blank" title="Zhihu" data-toggle=tooltip data-placement=top><i class="icon icon-zhihu"></i></a></li>
        
        <li><a href="https://segmentfault.com/u/hwame" target="_blank" title="Segmentfault" data-toggle=tooltip data-placement=top><i class="icon icon-segmentfault"></i></a></li>
        
        <li><a href="https://gitee.com/hwame" target="_blank" title="Gitee" data-toggle=tooltip data-placement=top><i class="icon icon-gitee"></i></a></li>
        
        <li><a href="/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        &copy; 2025 鴻塵
        
        
        <div class="publishby" style="font-family:Courier">
            <span id="busuanzi_container_site_pv">
                <i class="icon icon-eye"></i><span id="busuanzi_value_site_pv" style="font-family:Courier"></span>&nbsp;
                <i class="icon icon-users"></i><span id="busuanzi_value_site_uv" style="font-family:Courier"></span>
            </span>
            <!--
            <br>✯<a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/" style="color:#0FFFAA">鄂ICP备2020019329号</a>
            -->
            <br><i class="icon icon-clock" style="transform:rotate(90deg)"></i><span id="sitetime" style="font-family:Courier"></span>
        </div>
        
        <!--
        <div class="publishby">
        	Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.
        </div>
        -->
    </div>
    
</footer>
<script>
    function siteTime(){
        window.setTimeout("siteTime()", 1000);
        var seconds = 1000;
        var minutes = seconds * 60;
        var hours = minutes * 60;
        var days = hours * 24;
        var years = days * 365;
        var today = new Date();
        var todayYear = today.getFullYear();
        var todayMonth = today.getMonth()+1;
        var todayDate = today.getDate();
        var todayHour = today.getHours();
        var todayMinute = today.getMinutes();
        var todaySecond = today.getSeconds();
        /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
        year - 作为date对象的年份，为4位年份值
        month - 0-11之间的整数，做为date对象的月份
        day - 1-31之间的整数，做为date对象的天数
        hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
        minutes - 0-59之间的整数，做为date对象的分钟数
        seconds - 0-59之间的整数，做为date对象的秒数
        microseconds - 0-999之间的整数，做为date对象的毫秒数 */
        var t1 = Date.UTC(2020,05,19,21,20,52); //建站时间
        var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
        var diff = t2-t1;
        var diffYears = Math.floor(diff/years);
        var diffDays = Math.floor((diff/days)-diffYears*365);
        var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
        var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
        var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
        // 将「数字」转「补零字符串」
        var y = diffYears.toString()
        var d = diffDays.toString().padStart(3, '0')
        var h = diffHours.toString().padStart(2, '0')
        var m = diffMinutes.toString().padStart(2, '0')
        var s = diffSeconds.toString().padStart(2, '0')
        document.getElementById("sitetime").innerHTML=y+":"+d+":"+h+":"+m+":"+s;
    }
    siteTime();
</script>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<div id="go-top"></div>
<style type="text/css">
#go-top {
 width:40px;height:40px;
 background-color:#DDA0DD;
 position:relative;
 border-radius:20px;
 position:fixed;right:20px;bottom:50px;
 cursor:pointer;display:none;
}
#go-top:after {
 content:" ";
 position:absolute;left:14px;top:14px;
 border-top:2px solid #fff;border-right:2px solid #fff;
 width:12px;height:12px;
 transform:rotate(-45deg);
}
#go-top:hover {
 background-color:#8A2BE2;
}
</style>
<script>
$(function () {
  var top=$("#go-top");
  $(window).scroll(function () {
    ($(window).scrollTop() > 300) ? top.show(300) : top.hide(200);
    $("#go-top").click(function () {
      $('body,html').animate({scrollTop:0});
      return false();
    })
  });
});
</script>

<script src="/js/plugin.min.js"></script>


<script src="/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/js/insight.js"></script>





   




   
    

  <script src='/waline.js'></script>
  <link rel="stylesheet" type="text/css" href="/waline.css" />
  
  <script type="text/javascript">
 
  
Waline.init({
      el: '#vcomments',
      serverURL: 'https://waline.hwame.top',
});
  </script>

     


<!-- 20201211添加判断 -->

   
  <script src="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script>
  <script>
  //利用 FancyBox 实现点击图片放大
  $(document).ready(function() {
    $('article img').not('[hidden]').not('.panel-body img').each(function() {
      var $image = $(this);
      var imageCaption = $image.attr('alt');
      var $imageWrapLink = $image.parent('a');
      if ($imageWrapLink.length < 1) {
        var src = this.getAttribute('src');
        var idx = src.lastIndexOf('?');
        if (idx != -1) {
          src = src.substring(0, idx);
        }
        $imageWrapLink = $image.wrap('<a href="' + src + '"></a>').parent('a');
      }
      $imageWrapLink.attr('data-fancybox', 'images');
      if (imageCaption) {
        $imageWrapLink.attr('data-caption', imageCaption);
      }
    });
    $().fancybox({
      selector: '[data-fancybox="images"]',
      hash: false,
      loop: true,
    });
  });
  </script>







  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
      z-index: 2;
    }

    .highlight-wrap:hover .copy-btn,
        .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  
  <script>
    addLoadEvent(()=>{
      $('.highlight').each(function (i, e) {
        var $wrap = $('<div>').addClass('highlight-wrap')
        $(e).after($wrap)
        $wrap.append($('<button>').addClass('copy-btn').append('一键复制').on('click', function (e) {
          var code = $(this).parent().find(".code")[0].innerText
          
          var ta = document.createElement('textarea')
          document.body.appendChild(ta)
          ta.style.position = 'absolute'
          ta.style.top = '0px'
          ta.style.left = '0px'
          ta.value = code
          ta.select()
          ta.focus()
          var result = document.execCommand('copy')
          document.body.removeChild(ta)
          
            if(result)$(this).text('复制成功')
            else $(this).text('复制失败')
          
          $(this).blur()
        })).on('mouseleave', function (e) {
          var $b = $(this).find('.copy-btn')
          setTimeout(function () {
            $b.text('一键复制')
          }, 300)
        }).append(e)
      })
    })
  </script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html>